import { TOKEN } from '@/common/constant/sessionKey';
import { getItem, getToken } from '@/utils/auth'; // get token from cookie
import { getPageIcon, getPageTitle } from '@/utils/get-page-title';
import { Message } from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import router from './router';
import store from './store';

NProgress.configure({
    showSpinner: false
}); // NProgress Configuration

const whiteList = ['/login', '/forgetpsd', '/resetpwd', '/esign']; // no redirect whitelist

router.beforeEach(async(to, from, next) => {
    NProgress.start();

    // set page title
    // const formats_info = JSON.parse(getToken('formats_info') || '{}');
    // const icon = JSON.parse('./static/icon/09.jpg');
    // getPageTitle(to.meta.title, formats_info.name);
    getPageTitle(to.meta.title, '膏珍堂');
    // getPageIcon(icon);

    const token = getItem(TOKEN, false);
    if (token) {
        if (to.path === '/login') {
            next({ path: '/' });
        } else {
            const hasRoles = store.getters.roles && store.getters.roles.length > 0;
            // console.log(hasRoles);
            if (hasRoles) {
                // console.log(router);

                if (to.path === '/') {
                    // console.log(store.getters.menus);
                    next({ ...store.getters.menus[0] });
                } else {
                    next();
                }
            } else {
                try {
                    const roles = await store.dispatch('user/getInfo');
                    const accessRoutes = await store.dispatch('permission/generateRoutes', roles);
                    // console.log('3333', accessRoutes);
                    router.addRoutes(accessRoutes);
                    // console.log(router);
                    next({ ...to, replace: true });
                } catch (error) {
                    // console.log('permission', error);
                    store.dispatch('user/resetToken');
                    Message.error(error || 'Has Error');
                    next(`/login?redirect=${to.path}`);
                }
            }
        }
        NProgress.done();
    } else {
        if (whiteList.includes(to.path)) {
            next();
        } else {
            next(`/login?redirect=${to.path}`);
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    NProgress.done();
});
